<template>
  <div class="order-container">
    <div class="order-header">
      <h1>我的订单</h1>
      <button @click="goBack" class="back-btn">返回</button>
    </div>

    <div class="order-list-container">
      <div v-if="loading" class="loading">加载中...</div>
      <div v-else-if="errorMessage" class="error-message">{{ errorMessage }}</div>
      <div v-else-if="orderList.length === 0" class="empty-orders">
        <p>暂无订单</p>
        <button @click="goBack" class="go-shopping-btn">去购物</button>
      </div>
      <div v-else class="order-list">
        <div v-for="order in orderList" :key="order.id" class="order-card">
          <div class="order-card-header">
            <div class="order-info">
              <span class="order-no">订单号：{{ order.orderNo }}</span>
              <span class="order-time">{{ formatTime(order.createTime) }}</span>
            </div>
            <span :class="['order-status', getStatusClass(order.status)]">
              {{ order.statusDesc }}
            </span>
          </div>

          <div class="order-items">
            <div v-for="item in order.items" :key="item.id" class="order-item">
              <div class="item-info">
                <span class="item-name">{{ item.bookName }}</span>
                <span class="item-author" v-if="item.author">{{ item.author }}</span>
              </div>
              <div class="item-details">
                <span class="item-price">¥{{ item.price.toFixed(2) }}</span>
                <span class="item-quantity">× {{ item.quantity }}</span>
                <span class="item-subtotal">小计：¥{{ item.subtotal.toFixed(2) }}</span>
              </div>
            </div>
          </div>

          <div class="order-card-footer">
            <div class="order-total">
              <span>订单总额：</span>
              <span class="total-amount">¥{{ order.totalAmount.toFixed(2) }}</span>
            </div>
            <div class="order-actions">
              <button
                v-if="order.status === 0"
                @click="handlePay(order)"
                class="pay-btn"
                :disabled="payingOrderId === order.id"
              >
                <span v-if="payingOrderId === order.id">支付中...</span>
                <span v-else>立即支付</span>
              </button>
              <button
                v-if="order.status === 0"
                @click="handleCancelOrder(order)"
                class="cancel-btn"
                :disabled="cancelingOrderId === order.id"
              >
                <span v-if="cancelingOrderId === order.id">取消中...</span>
                <span v-else>取消订单</span>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getOrderList, cancelOrder } from '../api/order'

const router = useRouter()
const orderList = ref([])
const loading = ref(false)
const errorMessage = ref('')
const payingOrderId = ref(null)
const cancelingOrderId = ref(null)

onMounted(() => {
  loadOrders()
})

const loadOrders = async () => {
  loading.value = true
  errorMessage.value = ''

  try {
    const res = await getOrderList()
    if (res.code === 200) {
      orderList.value = res.data || []
    }
  } catch (error) {
    errorMessage.value = error.message || '加载订单列表失败'
    console.error('加载订单列表失败:', error)
  } finally {
    loading.value = false
  }
}

const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getStatusClass = (status) => {
  switch (status) {
    case 0:
      return 'status-pending'
    case 1:
      return 'status-paid'
    case 2:
      return 'status-cancelled'
    default:
      return ''
  }
}

const handlePay = async (order) => {
  if (!confirm(`确定要支付订单 ${order.orderNo} 吗？\n订单金额：¥${order.totalAmount.toFixed(2)}`)) {
    return
  }

  payingOrderId.value = order.id

  try {
    // 模拟支付过程
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    alert('支付成功！')
    
    // 刷新订单列表
    await loadOrders()
  } catch (error) {
    alert(error.message || '支付失败，请稍后重试')
    console.error('支付失败:', error)
  } finally {
    payingOrderId.value = null
  }
}

const handleCancelOrder = async (order) => {
  if (!confirm(`确定要取消订单 ${order.orderNo} 吗？`)) {
    return
  }

  cancelingOrderId.value = order.id

  try {
    const res = await cancelOrder(order.id)
    if (res.code === 200) {
      alert('订单已取消')
      await loadOrders()
    }
  } catch (error) {
    alert(error.message || '取消订单失败')
    console.error('取消订单失败:', error)
  } finally {
    cancelingOrderId.value = null
  }
}

const goBack = () => {
  router.push('/home')
}
</script>

<style scoped>
.order-container {
  min-height: 100vh;
  padding: 40px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 24px 32px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 24px;
}

.order-header h1 {
  color: #333;
  font-size: 28px;
  margin: 0;
}

.back-btn {
  padding: 10px 20px;
  background: #e0e0e0;
  color: #333;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.back-btn:hover {
  background: #d0d0d0;
}

.order-list-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 24px;
}

.loading,
.error-message {
  text-align: center;
  padding: 40px;
  color: #666;
  font-size: 16px;
}

.error-message {
  color: #f56565;
}

.empty-orders {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.empty-orders p {
  font-size: 16px;
  margin-bottom: 20px;
}

.go-shopping-btn {
  padding: 10px 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.go-shopping-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.order-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.order-card {
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  padding: 20px;
  transition: all 0.3s;
}

.order-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.order-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 16px;
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.order-no {
  font-weight: 600;
  color: #333;
  font-size: 16px;
}

.order-time {
  color: #999;
  font-size: 14px;
}

.order-status {
  padding: 6px 16px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
}

.status-pending {
  background: #fff3cd;
  color: #856404;
}

.status-paid {
  background: #d4edda;
  color: #155724;
}

.status-cancelled {
  background: #f8d7da;
  color: #721c24;
}

.order-items {
  margin-bottom: 16px;
}

.order-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.order-item:last-child {
  border-bottom: none;
}

.item-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  flex: 1;
}

.item-name {
  font-weight: 500;
  color: #333;
  font-size: 15px;
}

.item-author {
  color: #999;
  font-size: 13px;
}

.item-details {
  display: flex;
  align-items: center;
  gap: 16px;
}

.item-price {
  color: #666;
  font-size: 14px;
}

.item-quantity {
  color: #666;
  font-size: 14px;
}

.item-subtotal {
  color: #667eea;
  font-weight: 600;
  font-size: 14px;
  min-width: 100px;
  text-align: right;
}

.order-card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.order-total {
  font-size: 16px;
  color: #333;
}

.total-amount {
  color: #667eea;
  font-size: 20px;
  font-weight: 600;
  margin-left: 8px;
}

.order-actions {
  display: flex;
  gap: 12px;
}

.pay-btn {
  padding: 10px 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s;
}

.pay-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.pay-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.cancel-btn {
  padding: 10px 24px;
  background: #e0e0e0;
  color: #333;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.cancel-btn:hover:not(:disabled) {
  background: #d0d0d0;
}

.cancel-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>

